
<template>
  <el-form ref="form" :model="data" :rules="rules" label-width="100px" v-loading="loading">
                     <el-form-item label="示例文本" prop="demo_text">
                        <el-input v-model.trim="data.demo_text" placeholder="请填写示例文本" />
                    </el-form-item>
                     <el-form-item label="示例文本域">
                        <el-input type="textarea"  rows="3" v-model.trim="data.demo_textarea"></el-input>
                      </el-form-item>
                    <el-form-item label="示例数字" prop="demo_number">
                        <el-input-number v-model="data.demo_number" :min="1" :max="10" label="示例数字"></el-input-number>
                    </el-form-item>
                    <el-form-item label="示例密码" prop="demo_pass">
                        <el-input v-model.trim="data.demo_pass" show-password placeholder="请填写示例密码" />
                    </el-form-item>
                    <el-form-item label="示例单选">
                         <el-radio-group v-model="data.demo_radio">
                             <el-radio label="1">选项1</el-radio>
                             <el-radio label="2">选项2</el-radio>
                         </el-radio-group>
                    </el-form-item>
                    <el-form-item label="示例多选">
                         <el-checkbox-group v-model="data.demo_chekbox">
                             <el-checkbox label="1">选项1</el-checkbox>
                             <el-checkbox label="2">选项2</el-checkbox>
                         </el-checkbox-group>
                    </el-form-item>
                    <el-form-item label="示例下拉单选" prop="demo_select">
                    <el-select v-model.trim="data.demo_select" placeholder="请选择示例下拉单选" clearable  class="filter-item" >
                        <el-option  label="选项1" value="1"></el-option>
                    </el-select>
                    </el-form-item>
                    <el-form-item label="示例下拉多选" prop="demo_selects">
                    <el-select v-model.trim="data.demo_selects" multiple  placeholder="请选择示例下拉多选" clearable  class="filter-item" >
                        <el-option  label="选项1" value="1"></el-option>
                        <el-option  label="选项2" value="2"></el-option>
                    </el-select>
                    </el-form-item>
                    <el-form-item label="示例省市区" prop="demo_district">
                      <el-cascader
                        size="large"
                        :options="address_options"
                        clearable
                        filterable
                        placeholder="选择地区"
                        style="width: 250px;margin-right: 10px;"
                        v-model="selectedOptions"
                        @change="handleAddressChange">
                    </el-cascader>
                    </el-form-item>
                    <el-form-item label="示例单图" prop="demo_pic" >
                      <el-upload
                        class="avatar-uploader"
                        v-loading="data.demo_pic_loading"
                        element-loading-text="图片上传中"
                        :action="$store.state.settings.file_upload_url"
                        :headers ="headerObj"
                        :show-file-list="false"
                        accept="image/png, image/jpeg, image/gif, image/jpg"
                        :on-success="handledemo_picSuccess"
                        :before-upload="beforedemo_picUpload">
                            <img v-if="data.demo_pic !=''" :src="data.demo_pic" class="avatar">
                            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                        </el-upload>
                    </el-form-item>
                    <el-form-item label="示例多图" prop="demo_pics">
                        <el-upload
                    :action="$store.state.settings.file_upload_url"
                    :headers ="headerObj"
                    multiple
                    list-type="picture-card"
                    :on-preview="handledemo_picsPreview"
                    :file-list="data.demo_picsfileList"
                    accept="image/png, image/jpeg, image/gif, image/jpg"
                    :on-success="handledemo_picsSuccess"
                    :on-remove="handledemo_picsRemove"
                    >
                     <i class="el-icon-plus"></i>
                    </el-upload>
                    </el-form-item>
                    <el-form-item label="通用文件" prop="demo_files">
                        <el-upload
                    :action="$store.state.settings.file_upload_url"
                    :headers ="headerObj"
                    multiple
                    :file-list="data.demo_fileList"
                    accept="image/png, image/jpeg, image/gif, image/jpg,.csv,.xls,.xlsx,.doc,.docx,.ppt,.pptx,.pdf,.zip,.rar"
                    :on-success="handledemo_filesSuccess"
                    :on-remove="handledemo_filesRemove"
                    >
                     <el-button size="small" type="primary">点击上传</el-button>
                    </el-upload>
                    </el-form-item>
                    <el-form-item label="示例视频" prop="demo_video">
                        <el-upload
                    action="#"
                    ref="demo_video" :auto-upload="false" :file-list = "data.demo_videofileList" :on-change="videoChangedemo_video" class="avatar-uploader"  accept=".mp4" :on-remove="handleRemovedemo_video">
                    <video ref="demo_video"  v-if="data.demo_video"  controls style="width: 320px;height: 180px;" :src="data.demo_video"></video>
                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                        </el-upload>
                    <el-progress  v-show="data.demo_videopercentage>0 && data.demo_videopercentage<100" :percentage="data.demo_videopercentage" :text-inside="true" :stroke-width="18"></el-progress>
                    </el-form-item>
                    <!-- <el-form-item label="示例富文本" prop="demo_intro">
                         <tinymce
                    id="editorId"
                  ref="editor"
                  v-model="data.demo_intro"
                    @input="handleInput"
                    @onClick="handleClick"
                  />
                    </el-form-item> -->
                    <el-form-item label="示例富文本" prop="demo_intro" >
                       <editor v-if="this.item.dialogVisible" v-model="data.demo_intro"/>
                    </el-form-item>
                    <el-form-item label="示例日期">
                         <el-date-picker type="date" key="demo_date" value-format="yyyy-MM-dd" placeholder="请选择日期" v-model="data.demo_date"></el-date-picker>
                    </el-form-item>
                    <el-form-item label="示例时间">
                         <el-time-select  placeholder="请选择时间" v-model="data.demo_time"></el-time-select>
                    </el-form-item>
                    <el-form-item label="示例日期范围">
                         <el-date-picker type="daterange" value-format="yyyy-MM-dd" placeholder="请选择日期" start-placeholder="开始日期" end-placeholder="结束日期" range-separator="/" v-model="data.damo_range"></el-date-picker>
                    </el-form-item>
                    <el-form-item label="示例开关">
                             <el-switch v-model="data.demo_switch"></el-switch>
                    </el-form-item>
  
          <el-dialog :visible.sync="dialogVisible" width="30%" append-to-body>
              <img width="100%" :src="previewUrl" alt="">
          </el-dialog>  
    <el-form-item>
      <el-button type="primary" con="el-icon-check" :disabled="$store.state.settings.ajaxButton" @click="submit">提交</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import {detail,edit} from '@/api/demo'
import { getToken } from '@/utils/auth'
import videoUpload from '@/utils/videoUpload'
import {get_video_config,upload_file} from '@/api/common'
import  editor  from "@/components/Editor";
import { 
    provinceAndCityData, 
    regionData,
    provinceAndCityDataPlus, 
    regionDataPlus, 
    CodeToText, 
    TextToCode 
} from 'element-china-area-data'


export default {
  name: 'demoEdit',
  components: {editor },
  props: {
    item: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  data() {
    return {
      address_options: regionDataPlus,
      selectedOptions:[],
      loading:true,
      dialogVisible:false,
      previewUrl:'',
      headerObj: {
        'Authorization': 'Bearer ' + getToken()
        },
      rules: {
                    demo_text: [ 
                { required: true, message: "请输入示例文本", trigger: "blur" }
            ], 

      },
      data: {
            demo_pic_loading:false,
            import_url : process.env.VUE_APP_BASE_API+'/admin/demo_import',           
             demo_text:'',
             demo_textarea:'',
            demo_number:'',
            demo_pass:'',
            demo_radio:'1',
            demo_chekbox:['1'],
            demo_select:'',
            demo_selects:'',
            demo_pic:[],
            demo_picpreviewurl:'',
            demo_picfileList:[],
            demo_pics:[],
            demo_files:[],
            demo_picspreviewurl:'',
            demo_picsfileList:[],
            demo_fileList:[],
            demo_video:'',
            demo_videofileList:[],
            demo_videopercentage:0,
            demo_intro:'',
            demo_date:'2022-04-25',
            demo_time:'22-59',
            damo_range:[],
            demo_switch:true,

         }
    }
  },
  created() {
    const id = this.item.id
    this.id = id
    this.fetchData(id)
  },
  watch: {
    item: {
      handler(val, oldVal) {
        if (this.item.dialogVisible === true 
        ) {
          this.id = val.id
          this.fetchData(val.id)
        }
      },
      deep: true
    }
  },
  methods: {

    handleAddressChange (value) {
            let province = CodeToText[value[0]],
                city = CodeToText[value[1]],    
                area = CodeToText[value[2]];
                this.data.province = province !="全部" ? province : '';
                this.data.city = city != "全部" ? city : '';
                this.data.area = area != "全部" ? area : '';
        },
       handleExport(){
          export_excell(process.env.VUE_APP_BASE_API+'/admin/demo_exports',this.listQuery);
      },            handledemo_picExceed(){ 
                this.$message.error('只能上传一张图片');
             },
            handledemo_picPreview(file){
                 this.dialogVisible = true;
                 this.previewUrl = file.url;
             },
            handledemo_picRemove(){
                 this.data.demo_pic = '';
             },
             handledemo_picSuccess(response, file, fileList) {
                this.$store.commit('settings/SET_AJAX_BUTTON', false);
                this.data.demo_pic_loading = false 
                if(!response.data.src){
                    this.data.demo_pic = '';
                     return this.$message.error(response.msg);
                }
                  this.data.demo_pic= response.data.src;
            },
             beforedemo_picUpload(file) {
              this.data.demo_pic_loading = true 
                this.$store.commit('settings/SET_AJAX_BUTTON', true);
                const isJPG  = file.type === "image/jpeg";
                const isPNG  = file.type === "image/png";
 
                if (!isJPG && !isPNG) {
                 return this.$message.error("上传头像图片只能是 JPG 、PNG格式!");
                }
                this.$message.success('上传成功');
            },
             handledemo_picsPreview(file) {
                this.dialogVisible = true;
                this.previewUrl = file.url;
            },
             handledemo_picsRemove(file,fileList) {
              let index = this.data.demo_picsfileList.findIndex(item=>item.url==file.url);// 要删除的数组下标
              if(index!=-1) {
                this.data.demo_picsfileList.splice(index, 1);
                this.data.demo_pics.splice(index, 1);
              }
            },
             handledemo_picsSuccess(response, file, fileList) {
                 this.$store.commit('settings/SET_AJAX_BUTTON', false);
                  if(!response.data.src){
                    this.data.demo_picsfileList = [];
                     return this.$message.error(response.msg);
                }
                 this.data.demo_pics.push(response.data.src);
            },
             beforedemo_picsUpload(file) {
                this.$store.commit('settings/SET_AJAX_BUTTON', true);
                const isJPG = file.type === "image/jpeg";
                const isPNG = file.type === "image/png";
                if (!isLt2M) {
                this.$message.error("上传头像图片大小不能超过 2MB!");
                }
            },
        
             handledemo_filesRemove(file,fileList) {
                const that = this;
                const fileSrc = file.url
                this.data.demo_fileList.forEach(function(element,key) {
                if(element.url === fileSrc){
                that.data.demo_files.splice(key, 1);
                }
                });
            },
             handledemo_filesSuccess(response, file, fileList) {
                this.$store.commit('settings/SET_AJAX_BUTTON', false);
                 this.data.demo_files.push(response.data.src);
            },
             handledemo_filesSuccess(response, file, fileList) {
                 this.$store.commit('settings/SET_AJAX_BUTTON', false);
                 this.data.demo_files.push(response.data.src);
            },
              handleRemovedemo_video() {
                this.data.demo_video = "";
                this.data.demo_videofileList = [];
            },
        videoChangedemo_video(file, fileList) {
              var that = this;
            get_video_config().then(res=>{
                   if(res.code && res.code==1){ 
                       videoUpload.upload(res.data.uploadType,{
                           token: "",
                           file: file,
                           accessKeyId: res.data.accessKey,
                           accessKeySecret: res.data.secretKey,
                           bucketName:res.data.storageName,
                           region: res.data.storageRegion,
                           domain: res.data.uploadUrl,
                           static_path: res.data.static_path,
                           static_url :res.data.static_url,
                           uploadIng:function (progress) {
                                that.$set(that.data,"demo_videopercentage",progress);
                          }
                     }).then(function (res) {
                             that.data.demo_video = res.url;
                              that.$message.success("上传成功");
                              }).catch(function (err) {
                            that.$message.error(err);
                            });
                      }else if(res.data.uploadType =='local'){
                      //本地上传
                         const fd = new FormData()
                          fd.append('file', file.raw)
                          upload_file(fd,function(progress){
                            if(progress.lengthComputable){ //是否存在进度
                               var percentCompleted = Math.round( (progress.loaded * 100) / progress.total );
                               that.$set(that.data,"demo_videopercentage",percentCompleted);
                            }
                          }).then((res) => {
                             if(res.code ==1){
                               that.data.demo_video = res.data.src;
                             }else{
                                 that.$message.error(res.msg);
                             }
                          })
                  }else{
                    this.$message.error("获取上传配置失败，请检查");
                  }
             });
        },


    fetchData(id) {
          detail(id).then(response => {
            this.loading = false;
            this.data = response.data;
                        this.data.demo_chekbox=response.data.demo_chekbox ? response.data.demo_chekbox.split(','):[];
            this.data.demo_selects=response.data.demo_selects ? response.data.demo_selects.split(',').map(Number):[];
            this.data.demo_picfileList=response.data.demo_pic ? response.data.demo_pic.split(',').map(item=>{return{name:item,url:item}}):[];
            this.data.demo_pics=response.data.demo_pics ? response.data.demo_pics.split(',') : [];
            this.data.demo_files=response.data.demo_files ? response.data.demo_files.split(',') : [];
            this.data.demo_picsfileList=response.data.demo_pics ? response.data.demo_pics.map(item=>{return{name:item,url:item}}):[];
            this.data.demo_fileList=response.data.demo_files ? response.data.demo_files.map(item=>{return{name:item,url:item}}):[];
            this.data.demo_videofileList=response.data.demo_video ? [{name:response.data.demo_video,url:response.data.demo_video}] : [];
            this.data.damo_range=response.data.damo_range.split('/');
            this.data.demo_switch=response.data.demo_switch==1 ?true:false;
            this.selectedOptions =  TextToCode[response.data.province || ''][response.data.city || ''][response.data.area || ''].code
              console.log(this.data);
          }).catch(err => {
            console.log(err)
          })
        },
    submit() {
      const thiz = this
      this.$refs.form.validate(valid => {
        if (!valid) {
          return false
        }
        edit({
          id: this.data.id,
                        demo_text:this.data.demo_text,
            demo_number:this.data.demo_number,
            demo_pass:this.data.demo_pass,
            demo_radio:this.data.demo_radio,
            demo_chekbox:this.data.demo_chekbox.join(','),
            demo_select:this.data.demo_select,
            demo_selects:this.data.demo_selects.join(','),
            demo_pic:this.data.demo_pic,
            demo_pics:this.data.demo_pics.join(','),
            demo_files:this.data.demo_files.join(','),
            demo_video:this.data.demo_video,
            demo_intro:this.data.demo_intro,
            demo_date:this.data.demo_date,
            demo_time:this.data.demo_time,
            damo_range:this.data.damo_range.join('/'),
            demo_switch:this.data.demo_switch ?1:0,
            province : this.data.province,
            city : this.data.city,
            area : this.data.area,

        }).then(response => {
          this.$store.commit('settings/SET_AJAX_BUTTON', true);
          this.$message({
            message: '编辑成功',
            type: 'success',
            duration: 1500,
            onClose() {
              if (thiz.$refs.form !== undefined) {
                thiz.$refs.form.resetFields()
              }
              thiz.item.dialogVisible = false;
            }
          })
        })
      })
    }
  }
}
</script>
